/*
In case it matters, this code is hereby placed under the MIT/X11 License:

Copyright (c) 2011, Kevin A. Wortman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "exhaustive.h"

// typedef for the data type used to store bit counters.  An unsigned
// is probably limited to 32 bits but is portable.  On Unix you could
// use uint64_t for 64 bits, but that doesn't port to Windows (AFAIK).
typedef unsigned Bits;

// The number of bits in a Bits instance.
const int BITS_COUNT = sizeof(Bits) * 8;

// Helper function.  Return a Bits with bit index i set to 1 and all
// other bits set to 0.  The least significant bit is index 0.
inline Bits bit(int i) {
  assert(i >= 0);
  assert(i < BITS_COUNT);
  return static_cast<Bits>(1) << i;
}

PackageSet* exhaustiveKnapsack(const PackageVector& packages, int n, int W) {
  assert(n > 0);
  assert(n < packages.size());
  assert(n < BITS_COUNT);
  assert(W > 0);

  PackageSet* best = NULL;

  // This is translated directly from the pseudocode in the handout.
  Bits lastBitMask = bit(n) - 1;
  for (Bits bits = 0; bits <= lastBitMask; ++bits) {
    PackageSet* subset = new PackageSet(packages);
    for (int i = 0; i < n; ++i)
      if (bits & bit(i))
	    subset->insert(i);

    if (subset->totalSize() > W)
      continue;

    if ((best == NULL) || 
        (subset->totalVotes() > best->totalVotes())) 
    {
      if (best != NULL) 
      {
	// Need to delete best before reassinging the pointer!
	    delete best;
      }
      best = subset;
    } 
    else 
    {
      // This subset will never be used again.
      delete subset;
    }
  }

  return best;
}
